package com.yjt.fresh.fragment;
/*
 * 首页
 */

import android.Manifest;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.xuezj.cardbanner.CardBanner;
import com.xuezj.cardbanner.ImageData;
import com.yjt.fresh.R;
import com.yjt.fresh.activity.AtyBanner;
import com.yjt.fresh.activity.AtyHistoryDetail;
import com.yjt.fresh.activity.AtyLogin;
import com.yjt.fresh.activity.AtyMassages;
import com.yjt.fresh.activity.AtyProductCategory;
import com.yjt.fresh.activity.AtyProductDetail;
import com.yjt.fresh.activity.AtyProducts;
import com.yjt.fresh.activity.AtyQRScan;
import com.yjt.fresh.activity.AtySearch;
import com.yjt.fresh.adpater.AdpRvMainAtyHomePageCategory;
import com.yjt.fresh.adpater.AdpRvMainAtyHomePageHot;
import com.yjt.fresh.api.ApiGetAdverts;
import com.yjt.fresh.api.ApiGetAllCategories;
import com.yjt.fresh.api.ApiGetHistoryHome;
import com.yjt.fresh.api.ApiGetNewMassageCount;
import com.yjt.fresh.api.ApiGetProducts;
import com.yjt.fresh.base.BaseSimpleFragment;
import com.yjt.fresh.bean.BeanAdvert;
import com.yjt.fresh.bean.BeanGoodsCategories;
import com.yjt.fresh.bean.BeanHistory;
import com.yjt.fresh.bean.BeanProduct;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.SpaceItemDecorationVertical;
import com.yjt.fresh.widget.banner.MyImageLoader;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGABanner;


public class Frg_Home extends BaseSimpleFragment {


    private static final int MESSAGE_REQUEST_CODE = 1008;
    private static final int REQUEST_CODE = 1006;
    private final int CAMERA_REQUEST_CODE = 1;
    @BindView(R.id.tv_app_atymain_frg_homepage_city)
    TextView mTvCity;
    @BindView(R.id.ll_app_atymain_frg_homepage_search)
    LinearLayout mLlSearch;
    @BindView(R.id.iv_app_atymain_frg_homepage_message)
    ImageView mIvMessage;
    @BindView(R.id.rv_app_atymain_frg_homepage_category)
    RecyclerView mRvCategory;
    @BindView(R.id.rv_app_atymain_frg_homepage_hot)
    RecyclerView mRvHot;
    @BindView(R.id.srlAppAtyMainFrgHome)
    SwipeRefreshLayout mSrlRefresh;
    @BindView(R.id.tvAppFrgHomeNewMassageCount)
    TextView mTvNewMassageCount;
    @BindView(R.id.rlAppFrgHomeNewMassageCount)
    RelativeLayout mRlNewMassageCount;
    /*@BindView(R.id.bannerFrgHome)
    CardBanner mBannerLayout;*/
    @BindView(R.id.banner_guide_content)
    BGABanner mContentBanner;
    private AdpRvMainAtyHomePageHot mAdpHot;
    private AdpRvMainAtyHomePageCategory mAdpCategory;
    private List<BeanGoodsCategories> mCategoryList;
    private List<BeanProduct> mProductList;
    private boolean isBannerComplete;
    private boolean isCategoryComplete;
    private boolean isHotComplete;
    private LocalBroadcastManager mBroadcastManager;
    private BeanHistory mBeanHistory;

    public LocationClient mLocationClient = null;
    private MyLocationListener myLocationListener = new MyLocationListener();

    @Override
    protected int getContentView() {
        return R.layout.app_atymain_frg_homepage;
    }

    @Override
    protected void initView(Bundle savedInstanceState, View view) {
        ButterKnife.bind(this, view);
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        ViewGroup.LayoutParams layoutParams = mContentBanner.getLayoutParams();
        layoutParams.height = (int) (width/2.67);
        mContentBanner.setLayoutParams(layoutParams);

    }

    @Override
    protected void initEvents() {
        initLocation();
        initCategoryRV();
        initHotRV();
        initClick();
        getData();
        initRefresh();
        initBroadCast();
    }

    private void initLocation() {
        mLocationClient = new LocationClient(getContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myLocationListener);
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(1000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false
        option.setIsNeedAddress(true);
        option.setAddrType("all");
        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
        mLocationClient.start();


    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (!TextUtils.isEmpty(location.getCity())) {
                PreferenceManager preferenceManager = PreferenceManager.getInstance();
                preferenceManager.setCity(location.getCity());
                preferenceManager.setLongitude(String.valueOf(location.getLongitude()));
                preferenceManager.setLatitude(String.valueOf(location.getLatitude()));
                mAdpHot.setLocation(location.getLatitude(), location.getLongitude());
                mTvCity.setText(location.getCity());
                mLocationClient.unRegisterLocationListener(myLocationListener);
                mLocationClient.stop();
            }
        }
    }

    private void initCategoryRV() {
        GridLayoutManager categoryLayoutManager = new GridLayoutManager(mContext, 5);
        mRvCategory.setLayoutManager(categoryLayoutManager);
        mCategoryList = new ArrayList<>();
        mRvCategory.setHasFixedSize(true);
        mRvCategory.setNestedScrollingEnabled(false);
        mAdpCategory = new AdpRvMainAtyHomePageCategory(R.layout.app_recycle_item_homepage_category, mCategoryList);
        mRvCategory.setAdapter(mAdpCategory);

    }

    private void initHotRV() {
        LinearLayoutManager categoryLayoutManager = new LinearLayoutManager(mContext);
        categoryLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvHot.setLayoutManager(categoryLayoutManager);
        mRvHot.setHasFixedSize(true);
        mRvHot.setNestedScrollingEnabled(false);
        mProductList = new ArrayList<>();
        mRvHot.addItemDecoration(new SpaceItemDecorationVertical(CommonsToolsHelper.dip2px(mContext, 15)));
        mAdpHot = new AdpRvMainAtyHomePageHot(R.layout.app_recycle_item_homepage_hot, mProductList);
        mRvHot.setAdapter(mAdpHot);
    }


    private void initClick() {
        mAdpHot.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, AtyProductDetail.class);
                intent.putExtra(MyConstants.GOODS_ID, mAdpHot.getItem(position).getGOODS_ID());
                startActivity(intent);
            }
        });

        mAdpCategory.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == mAdpCategory.getData().size() - 1) {
                    Intent intent = new Intent(mContext, AtyProductCategory.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, AtyProducts.class);
                    intent.putExtra(MyConstants.SEARCH_OR_CATEGORY, MyConstants.CATEGORY);
                    intent.putExtra(MyConstants.PRODUCT_FIRST_TYPE, mAdpCategory.getItem(position).getTITLE());
                    startActivity(intent);
                }
            }
        });

        mLlSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtySearch.class);
                startActivity(intent);
            }
        });

        mIvMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyMassages.class);
                    startActivityForResult(intent, MESSAGE_REQUEST_CODE);
                } else {
                    loginDialog();
                }*/
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    // 第一次请求权限时，用户如果拒绝，下一次请求shouldShowRequestPermissionRationale()返回true
                    ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE);

                } else {
                    Intent intent = new Intent(mContext, AtyQRScan.class);
                    startActivityForResult(intent, REQUEST_CODE);
                }

            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(mContext, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            } else {
                Toast.makeText(mContext, "相机权限已被禁止", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void getData() {
        getBannerData();
        getCategoryData();
        getHotProducts();
//        getNewMassageCount();
        getHistory();
    }

    HttpOnNextListener<BeanHistory> mHomeListener = new HttpOnNextListener<BeanHistory>() {
        @Override
        public void onNext(BeanHistory beanHistory) {
            mBeanHistory = beanHistory;
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void getHistory() {
        ApiGetHistoryHome apiGetHistoryHome = new ApiGetHistoryHome(mHomeListener, mContext, true, false, false);
        HttpManager.getInstance().doHttpDeal(apiGetHistoryHome);
    }

    HttpOnNextListener<List<BeanAdvert>> mAdvertListener = new HttpOnNextListener<List<BeanAdvert>>() {
        @Override
        public void onNext(final List<BeanAdvert> beanAdverts) {
            isBannerComplete = true;
            if (isCategoryComplete && isHotComplete) {
                mSrlRefresh.setRefreshing(false);
            }

//            List<ImageData> imageDataList = new ArrayList<>();
            List<String> imageList = new ArrayList<>();
            for (int i = 0; i < beanAdverts.size(); i++) {
                /*ImageData imageData = new ImageData();
                imageData.setImage(beanAdverts.get(i).getCOVER_IMG());
                imageData.setSubtitleTitle("");
                imageDataList.add(imageData);*/
                imageList.add(beanAdverts.get(i).getCOVER_IMG());
            }

            /*mBannerLayout.setDatas(imageDataList).setCardImageLoader(new MyImageLoader()).setPlay(true).start();
            mBannerLayout.setOnItemClickListener(new CardBanner.OnItemClickListener() {
                @Override
                public void onItem(int position) {
                    Intent intent = new Intent(mContext, AtyBanner.class);
                    intent.putExtra(MyConstants.BANNER_OBJ, beanAdverts.get(position));
                    startActivity(intent);
                }
            });*/
            mContentBanner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
                @Override
                public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                    Glide.with(mContext)
                            .load(model)
                            .placeholder(R.mipmap.image_default)
                            .error(R.mipmap.image_default)
                            .dontAnimate()
                            .into(itemView);
                }
            });

            mContentBanner.setData(imageList,null);
            mContentBanner.setDelegate(new BGABanner.Delegate() {
                @Override
                public void onBannerItemClick(BGABanner banner, View itemView, @Nullable Object model, int position) {
                    if (beanAdverts.get(position).getTYPE() != 3) {
                        Intent intent = new Intent(mContext, AtyBanner.class);
                        intent.putExtra(MyConstants.BANNER_OBJ, beanAdverts.get(position));
                        startActivity(intent);
                    }else if (beanAdverts.get(position).getTYPE() == 3){
                        Intent intent = new Intent(mContext, AtyProductDetail.class);
                        intent.putExtra(MyConstants.GOODS_ID, beanAdverts.get(position).getSKIP_URL());
                        startActivity(intent);
                    }
                }
            });

        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };
    private void getBannerData() {
        ApiGetAdverts apiGetAdverts = new ApiGetAdverts(mAdvertListener, mContext, false, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("POSITION", 1);
        apiGetAdverts.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetAdverts);
    }


    HttpOnNextListener<List<BeanGoodsCategories>> mCategoriesListener = new HttpOnNextListener<List<BeanGoodsCategories>>() {
        @Override
        public void onNext(List<BeanGoodsCategories> beanGoodsCategories) {
            isCategoryComplete = true;
            if (isBannerComplete && isHotComplete) {
                mSrlRefresh.setRefreshing(false);
            }
            /*mCategoryList.clear();
            for (int i = 0; i < beanGoodsCategories.size(); i++) {
                if ("1".equals(beanGoodsCategories.get(i).getIS_SHOW_TYPE())) {
                    mCategoryList.add(beanGoodsCategories.get(i));
                }
            }
            mCategoryList.add(new BeanGoodsCategories());*/
            if (beanGoodsCategories.size() > 9) {
                List<BeanGoodsCategories> list = new ArrayList<>();
                for (int i = 0; i < 9; i++) {
                    list.add(beanGoodsCategories.get(i));
                }
                list.add(new BeanGoodsCategories());
                mAdpCategory.setNewData(list);
            } else {
                mAdpCategory.setNewData(beanGoodsCategories);
            }
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void getCategoryData() {
        ApiGetAllCategories apiGetAllCategories = new ApiGetAllCategories(mCategoriesListener, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("POSITION", 0);
        apiGetAllCategories.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetAllCategories);
    }


    HttpOnNextListener<List<BeanProduct>> mProductsListener = new HttpOnNextListener<List<BeanProduct>>() {
        @Override
        public void onNext(List<BeanProduct> beanProducts) {
            isHotComplete = true;
            mProductList.clear();
            if (isBannerComplete && isCategoryComplete) {
                mSrlRefresh.setRefreshing(false);
            }
            mProductList.addAll(beanProducts);
            mAdpHot.notifyDataSetChanged();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void getHotProducts() {
        ApiGetProducts apiGetProducts = new ApiGetProducts(mProductsListener, mContext, true, false, false);
        Map<String, String> map = new HashMap<>();
        map.put("currentPage", 1 + "");
        map.put("IS_INDEX", 1 + "");
        map.put("GOODSHOWPLACE", 1 + "");
        apiGetProducts.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetProducts);
    }

    HttpOnNextListener<Integer> mNewMassageCountListener = new HttpOnNextListener<Integer>() {
        @Override
        public void onNext(Integer integer) {
            if (integer > 0) {
                mRlNewMassageCount.setVisibility(View.VISIBLE);
                mTvNewMassageCount.setText(integer + "");
            } else {
                mRlNewMassageCount.setVisibility(View.GONE);
            }


        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void getNewMassageCount() {
        if (PreferenceManager.getInstance().getIsLogin()) {
            ApiGetNewMassageCount apiGetNewMassageCount = new ApiGetNewMassageCount(mNewMassageCountListener, mContext, true, false, false);
            Map<String, Object> map = new HashMap<>();
            map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
            apiGetNewMassageCount.setMap(map);
            HttpManager.getInstance().doHttpDeal(apiGetNewMassageCount);
        } else {
            mRlNewMassageCount.setVisibility(View.GONE);
        }
    }

    private void initRefresh() {
        mSrlRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isBannerComplete = false;
                isCategoryComplete = false;
                getData();
            }
        });
    }

    /*注册广播接收登录或者注销信息*/
    private void initBroadCast() {
        IntentFilter intentFilter = new IntentFilter(MyConstants.LOGIN_LOCAL_BROADCAST);
        mBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        mBroadcastManager.registerReceiver(mLocalReceiver, intentFilter);
    }

    BroadcastReceiver mLocalReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int optType = intent.getIntExtra(MyConstants.JUMP_TYPE, 0);
            if (optType == MyConstants.LOGIN) {
//                getNewMassageCount();
            } else if (optType == MyConstants.LOGOUT) {
                mRlNewMassageCount.setVisibility(View.GONE);
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mBroadcastManager.unregisterReceiver(mLocalReceiver);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    private void loginDialog() {

        final Dialog dialog = new Dialog(mContext, R.style.MyDialog);
        dialog.setContentView(R.layout.app_dialog_sure_cancel);
        TextView tvContent = dialog.findViewById(R.id.tvAppDIalogSureCancelContent);
        TextView tvCancel = dialog.findViewById(R.id.tvAppDialogSureCancelCancel);
        TextView tvSure = dialog.findViewById(R.id.tvAppDialogSureCancelSure);
        tvContent.setText("登录后才可以查看个人信息哦,亲~");
        tvCancel.setText("先不看");
        tvSure.setText("我要登录");
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtyLogin.class);
                startActivity(intent);
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getData();
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (result.contains(":")) {
                        Intent intent = new Intent(mContext, AtyHistoryDetail.class);
                        intent.putExtra(MyConstants.SOURCE_SID, result.split(":")[1]);
                        intent.putExtra(MyConstants.VIDEO_OBJ, mBeanHistory);
                        startActivity(intent);
                    } else {
                        Toast.makeText(mContext, "解析二维码失败", Toast.LENGTH_LONG).show();
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(mContext, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }

    }
}
